package com.chen.day01_base;

import java.util.concurrent.CompletableFuture;

class DataBuffer {
    private int data;
    private boolean available = false;  // 数据是否可用

    // 生产者调用此方法来生产数据
    public synchronized void produce(int data) throws InterruptedException {
        // 如果数据已存在，等待消费者消费
        while (available) {
            wait();  // 生产者等待
        }
        this.data = data;   // 生产数据
        available = true;   // 数据已可用
        System.out.println("Produced: " + data);
        notify();  // 唤醒消费者线程
    }

    // 消费者调用此方法来消费数据
    public synchronized int consume() throws InterruptedException {
        // 如果数据不可用，等待生产者生产数据
        while (!available) {
            wait();  // 消费者等待
        }
        available = false;  // 数据已消费
        System.out.println("Consumed: " + data);
        notify();  // 唤醒生产者线程
        return data;
    }
}

class Producer implements Runnable {

    private DataBuffer buffer;

    public Producer(DataBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                buffer.produce(i);  // 生产数据
                Thread.sleep(2000);  // 模拟生产的延迟
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private DataBuffer buffer;

    public Consumer(DataBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        CompletableFuture<Void> exceptionally = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            return "Hello";
        }).thenApply(result -> result + " World")
                .thenAccept(System.out::println)
                .exceptionally(e -> {
                    System.err.println("Error: " + e.getMessage());
                    return null;
                });
        CompletableFuture.allOf(exceptionally).join();
//        CompletableFuture.
        try {
            for (int i = 1; i <= 5; i++) {
                buffer.consume();  // 消费数据
                Thread.sleep(5000);  // 模拟消费的延迟
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ProducerConsumerExample {
    public static void main(String[] args) {
        DataBuffer buffer = new DataBuffer();  // 创建共享的缓冲区
        Thread producerThread = new Thread(new Producer(buffer));  // 创建生产者线程
        Thread consumerThread = new Thread(new Consumer(buffer));  // 创建消费者线程

        producerThread.start();
        consumerThread.start();
    }
}
